package com.wzy.redisdemo.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("/redis")
@RestController
public class RedisController {

    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping("/set")
    public boolean redisSet(String key, String value){

        try {
            redisTemplate.opsForValue().set(key,value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @RequestMapping("/get")
    public Object redisGet(String key){
        return redisTemplate.opsForValue().get(key);
    }

    @RequestMapping("/expire")
    public boolean expire(String key){
        return redisTemplate.expire(key,60,TimeUnit.SECONDS);
    }

    @RequestMapping("setObj")
    public boolean redisSetObject(String key){
        Map<String,Object> map = new HashMap<>();
        map.put("id",1);
        map.put("name","wzy");
        map.put("age",18);
        map.put("createDate",new Date());

        try {
            redisTemplate.opsForValue().set(key,map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
